/**
 * SpellManager
 * Manage spell entities
 **/
var SpellManager = function() {
	this.spells = [];
	this.entities = [];

	this.init = function() {
		this.load();
	}

	this.update = function() {
		this.garbage();
		for(var iE = 0, c = this.entities.length; iE < c; iE++) {
			this.entities[iE].update();
		}
	}

	this.render = function() {
		for(var iE = 0, c = this.entities.length; iE < c; iE++) {
			this.entities[iE].render();
		}
	}

	this.garbage = function() {
		for(var iE = 0, cE = this.entities.length; iE < cE; iE++) {
			if(this.entities[iE].toGarbage == true) {
				this.entities[iE].anim.destroy();
				this.entities.splice(iE, 1);
				cE--;
			}
		}
	}

	this.load = function() {
		var data = localStorage.getItem('spellbook');
		var spellbook = JSON.parse(data);
		
		if(spellbook != null) {
			for(s in spellbook) {
				var spell = new Spell();
				spell.unserialize(spellbook[s]);

				for(prop in spell) {
					if (isNumber(spell[prop]) && typeof SpellConf[prop] != "undefined") {
						spell[prop] = spell[prop] > SpellConf[prop].max ? SpellConf[prop].max : spell[prop];
						spell[prop] = spell[prop] < SpellConf[prop].min ? SpellConf[prop].min : spell[prop];
					}
				}

				spell.cooldown = spell.getCooldown();

				this.spells.push(spell);
			}
		}
	}

	this.deleteOne = function(instance) {
		// Delete an instance of spell
		for(var iS = 0, c = this.spells.length; iS < c; iS++) {
			if(this.spells[iS] === instance) {
				this.spells.remove(iS);
				c--;
			}
		}
	}

	this.save = function() {

		var spellbook = {};

		// Parse all spell created
		for(var iS = 0, c = this.spells.length; iS < c; iS++) {
			var spell = this.spells[iS];
			// Serialize object into json
			spellbook[spell.name] = spell.serialize();
		}
		// Convert spellbook object into json
		var json = JSON.stringify(spellbook);
		// Save json in local storage
		localStorage.setItem('spellbook', json);

		log("SAVE SPELLBOOK AS JSON : " + json);
	}
};